<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-tree :default-expand-all="true" :data="deptOptions" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
      </el-col>
      <el-col :span=20>
        <div>
          <el-button size="mini" @click="handleAdd()">新增</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="用户名称" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户昵称" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.nickName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.deptName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.phone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="left">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- dialog 模态框 -->
    <el-dialog
      :title="dialogInfo.title"
      :visible.sync="dialogInfo.dialogVisible"
      :width="dialogInfo.width"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="ruleForm.nickName" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect
            v-model="ruleForm.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级部门"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="ruleForm.gender" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="jobId">
          <el-select v-model="ruleForm.jobId" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in jobOptions"
              :key="item.jobId"
              :label="item.jobName"
              :value="item.jobId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="ruleForm.roleIds" placeholder="请选择" multiple style="width: 100%">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogInfo.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDeptTree } from "@/api/system/dept";
import { getJobAllList } from "@/api/system/job";
import { getDictItems } from "@/api/system/dict";
import { getAllRoleList } from "@/api/system/role";
import { addUser, getUserList, getRoleIdsByUserId, updateUser, deleteUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  name: "user",
  data() {
    return {
      data: [],
      tableData: [],
      deptOptions: [],
      genderOptions: [], // 性别
      jobOptions: [], // 岗位
      roleOptions: [], // 角色
      total: 0,
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        deptId: 0
      },
      dialogInfo: {
        dialogVisible: false,
        title: "",
        width: "30%"
      },
      ruleForm: {
        userId: "",
        nickName: "",
        deptId: undefined,
        phone: "",
        email: "",
        username: "",
        password: "",
        gender: "",
        jobId: "",
        roleIds: [],
        remark: ""
      },
      rules: {
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" }
        ],
        deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
        phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" }
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        job: [{ required: true, message: "请选择岗位", trigger: "change" }],
        roleIds: [
          {
            type: "array",
            required: true,
            message: "请选择角色",
            trigger: "change"
          }
        ],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
      },
      defaultProps: {
        children: "children",
        label: "deptName",
        id: "deptId"
      }
    };
  },
  created() {
    this.getList();
    // 获取字典选项
    getDictItems({ dictType: "sys_gender" }).then(resp => {
      if (resp.code == 0) {
        this.genderOptions = resp.data.item;
      }
    });
    this.getDeptTree();
  },
  methods: {
    handleNodeClick(data) {
      this.queryParams.deptId = data.deptId
      this.getList()
    },
    getList() {
      getUserList(this.queryParams).then(resp => {
        if (resp.code == 0) {
          this.tableData = resp.data.item;
          this.total = resp.data.total;
        }
      });
    },
    // 打开dialog
    handleAdd() {
      this.dialogInfo.title = "新增";
      this.dialogInfo.dialogVisible = true;
      this.getDeptTree();
      this.getJobAllList();
      this.getAllRoleList();
      this.resetForm();
      this.clearValidate("ruleForm");
      // this.getMenuElementUiTree();
    },
    // 每页条目数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    // 页数变化
    handleCurrentChange(val) {
      this.queryParams.pageIndex = val;
      this.getList();
    },
    // 获取部门tree
    getDeptTree() {
      getDeptTree().then(resp => {
        if (resp.code == 0) {
          this.deptOptions = resp.data.deptTree;
        }
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getJobAllList() {
      getJobAllList().then(resp => {
        if (resp.code == 0) {
          this.jobOptions = resp.data.item;
        }
      });
    },
    handleEdit(index, row) {
      // 打开dialog
      this.dialogInfo.title = "编辑";
      this.dialogInfo.dialogVisible = true;
      this.clearValidate("ruleForm");
      this.ruleForm.userId = row.userId;
      this.ruleForm.username = row.username;
      this.ruleForm.password = row.password;
      this.ruleForm.nickName = row.nickName;
      this.ruleForm.phone = row.phone;
      this.ruleForm.salt = row.salt;
      this.ruleForm.phone = row.phone;
      this.ruleForm.avatar = row.avatar;
      this.ruleForm.gender = row.gender;
      this.ruleForm.email = row.email;
      this.ruleForm.remark = row.remark;
      this.ruleForm.deptId = row.deptId;
      this.ruleForm.jobId = row.jobId;
      this.getAllRoleList();
      this.getRoleIdsByUserId(row.userId)
      this.getJobAllList();
      console.log(this.ruleForm)
    },
    // 移除表单项的校验结果
    clearValidate(formName) {
      this.$nextTick(function() {
        // DOM 现在更新了
        // `this` 绑定到当前实例
        this.$refs[formName].clearValidate();
      });
    },
    // 删除
    handleDelete(index, row) {
      deleteUser(row.userId).then(resp => {
        if (resp.code == 0) {
          this.notifySuccess(resp.message);
          this.getList();
        }
      });
    },
    getAllRoleList() {
      getAllRoleList().then(resp => {
        if (resp.code == 0) {
          this.roleOptions = resp.data.item;
        }
      });
    },
    getRoleIdsByUserId(userId) {
      getRoleIdsByUserId({userId}).then(resp => {
        if (resp.code == 0) {
          this.ruleForm.roleIds = resp.data.item
        }
      })
    },
    // 提交
    submitForm() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          // 判断是增加还是修改
          if (this.dialogInfo.title == "新增") {
            let obj = {
              nickName: this.ruleForm.nickName,
              deptId: this.ruleForm.deptId,
              phone: this.ruleForm.phone,
              email: this.ruleForm.email,
              username: this.ruleForm.username,
              password: this.ruleForm.password,
              gender: this.ruleForm.gender,
              jobId: this.ruleForm.jobId,
              remark: this.ruleForm.remark,
              roleIds: this.ruleForm.roleIds
            };
            addUser(obj).then(resp => {
              if (resp.code == 0) {
                this.notifySuccess(resp.message);
                this.closeDialog();
                // this.getList();
              } else {
                this.notifyErr(resp.message);
              }
            });
          } else {
            console.log(this.ruleForm)
            updateUser(this.ruleForm).then(resp => {
              if (resp.code == 0) {
                this.notifySuccess(resp.message);
                this.closeDialog();
                this.getList();
              } else {
                this.notifyErr(resp.message);
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 关闭dialog
    closeDialog() {
      this.dialogInfo.dialogVisible = false;
    }
  }
};
</script>